<template>
  <!-- @好友组件 -->
  <div class="mention_friend_component">
    <div class="mention_friend_component_hd">
      <div class="hd_lf" @click="model = false">
        <Icon name="zuojiantou" color="#fff" size="16"></Icon>
      </div>
      <h5 class="hd_title">@好友</h5>
    </div>

    <!-- 浮动标题 -->
    <div class="fixed_letter_wrap" v-if="currentFixedLetter">
      <div class="fixed_letter">{{ currentFixedLetter }}</div>
    </div>

    <div class="comment_list_wrap" ref="listWrap">
      <div class="comment_list_wrap_search">
        <div class="input_wrap">
          <div class="lf">
            <Icon name="search1" color="#a6a5a4" size="21"></Icon>
          </div>
          <input placeholder="搜索用户昵称" class="input" ref="InputRef" v-model="InputVal" />
          <div class="rt" v-if="isShow">
            <Icon name="close" color="#a6a5a4" size="12"></Icon>
          </div>
        </div>
      </div>

      <div class="list">
        <div class="list_item_wrap" v-for="(users, letter) in mentionFriendListGrouped" :key="letter"
          :data-letter="letter" ref="listItemWrap">
          <!-- 字母标题 -->
          <div class="list_item_letter" :ref="`letter-${letter}`">{{ letter }}</div>

          <!-- 用户列表 -->
          <div class="list_item" v-for="user in users" :key="user.userId" @click="selectUser(user)">
            <div class="item_content">
              <div class="item_avatar">
                <img :src="user.userAvatar" alt="" />
              </div>
              <div class="item_info">
                <div class="item_name">{{ user.userNickname }}</div>
                <div class="item_label">{{ user.userDesc }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="Letterinquiry">
      <div class="Letterinquiry_Icon" @click="InputFn" :class="{ 'highlight': isSearchHighlighted }">
        <Icon name="search1" :color="isSearchHighlighted ? '#2180ca' : '#a6a5a4'" size="19"></Icon>
      </div>
      <div class="Letterinquiry_item" :class="{ 'highlight': letter === selectedLetter }"
        v-for="letter in letterIndexList" :key="letter" @click="scrollToLetter(letter)">
        <div class="item_letter">{{ letter }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Icon from '@/components/common/Icon.vue'
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { pinyin } from 'pinyin'
import { getFriendListAPI } from '@/api/FriendList'
import { useUserStore } from '@/stores/userinfo'
const userStore = useUserStore()
const { userId } = userStore.userInfo

// 内部状态
const InputVal = ref('')
const model = defineModel({ type: Boolean, default: false })
const emit = defineEmits(['postselectUser'])

// 新增：内部好友列表
const mentionFriendList = ref([])

// 输入框引用
const InputRef = ref(null)
const isShow = computed(() => InputVal.value !== '')

// 获取首字母
function getFirstLetter(str) {
  if (!str || typeof str !== 'string') return '#'
  const trimmed = str.trim()
  if (!trimmed) return '#'

  const firstChar = trimmed[0]
  if (/[a-zA-Z]/.test(firstChar)) {
    return firstChar.toUpperCase()
  }
  if (/[\u4e00-\u9fa5]/.test(firstChar)) {
    const result = pinyin(firstChar, {
      style: pinyin.STYLE_FIRST_LETTER,
      heteronym: false,
      segment: true
    })
    return result[0]?.[0]?.toUpperCase() || '#'
  }
  return '#'
}

// 分组逻辑（带搜索过滤）
const filteredMentionFriendList = computed(() => {
  const val = InputVal.value.trim().toLowerCase()
  if (!val) return mentionFriendList.value

  return mentionFriendList.value.filter(user =>
    user.userNickname.toLowerCase().includes(val)
  )
})

const mentionFriendListGrouped = computed(() => {
  const groups = {}
  filteredMentionFriendList.value.forEach(item => {
    const letter = getFirstLetter(item.userNickname)
    if (!groups[letter]) groups[letter] = []
    groups[letter].push(item)
  })

  const sortedKeys = Object.keys(groups)
    .filter(key => key !== '#')
    .sort()
    .concat(['#'])

  return sortedKeys.reduce((acc, key) => {
    acc[key] = groups[key]
    return acc
  }, {})
})

const letterIndexList = computed(() => {
  const keys = Object.keys(mentionFriendListGrouped.value)
    .filter(key => key !== '#')
    .sort()
    .concat(['#'].filter(k => mentionFriendListGrouped.value[k]))
  return keys
})

// 滚动相关
const currentFixedLetter = ref(null)
const listWrap = ref(null)
const selectedLetter = ref(null)
const isSearchHighlighted = ref(true)
const isProgrammaticScrolling = ref(false)

const scrollToLetter = (letter) => {
  selectedLetter.value = letter
  currentFixedLetter.value = letter
  isSearchHighlighted.value = false
  isProgrammaticScrolling.value = true

  const element = document.querySelector(`[data-letter="${letter}"]`)
  if (element && listWrap.value) {
    const letterElement = element.querySelector('.list_item_letter')
    const rect = letterElement.getBoundingClientRect()
    const listWrapRect = listWrap.value.getBoundingClientRect()
    const scrollTop = listWrap.value.scrollTop
    const letterTop = rect.top - listWrapRect.top + scrollTop

    listWrap.value.scrollTo({
      top: letterTop,
      behavior: 'smooth'
    })

    setTimeout(() => {
      isProgrammaticScrolling.value = false
    }, 500)
  }
}

// 节流
const throttle = (func, delay) => {
  let timer = null
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        func.apply(this, args)
        timer = null
      }, delay)
    }
  }
}

const handleScroll = () => {
  if (!listWrap.value || isProgrammaticScrolling.value) return

  const scrollTop = listWrap.value.scrollTop
  const letterElements = document.querySelectorAll('.list_item_letter')
  if (letterElements.length === 0) return

  const letters = Array.from(letterElements).map(el => {
    const rect = el.getBoundingClientRect()
    const listWrapRect = listWrap.value.getBoundingClientRect()
    return {
      text: el.textContent.trim(),
      top: rect.top - listWrapRect.top + scrollTop,
      bottom: rect.bottom - listWrapRect.top + scrollTop
    }
  })

  const sortedLetters = letters.sort((a, b) => {
    if (a.text === '#' && b.text !== '#') return 1
    if (a.text !== '#' && b.text === '#') return -1
    return a.text.localeCompare(b.text)
  })

  let targetLetter = null
  if (scrollTop < 10) {
    targetLetter = null
  } else {
    for (let i = 0; i < sortedLetters.length; i++) {
      const { top, bottom, text } = sortedLetters[i]
      if (top <= scrollTop && bottom > scrollTop) {
        targetLetter = text
        break
      } else if (top <= scrollTop && bottom <= scrollTop && i === sortedLetters.length - 1) {
        targetLetter = text
      } else if (top > scrollTop && targetLetter === null && i > 0) {
        targetLetter = sortedLetters[i - 1].text
        break
      }
    }
  }

  if (currentFixedLetter.value !== targetLetter) {
    currentFixedLetter.value = targetLetter
    selectedLetter.value = targetLetter
    isSearchHighlighted.value = targetLetter === null
  }
}

const throttledHandleScroll = throttle(handleScroll, 50)

// 请求数据
onMounted(async () => {
  try {
    const res = await getFriendListAPI(userId)
    res.data.forEach(item => {
      item.userAvatar = 'http://43.138.15.137:3000' + item.userAvatar
    })
    mentionFriendList.value = res.data || []
    console.log(mentionFriendList.value)
  } catch (error) {
    console.error('获取好友列表失败:', error)
    mentionFriendList.value = []
  }

  // 绑定滚动
  if (listWrap.value) {
    listWrap.value.addEventListener('scroll', throttledHandleScroll)
  }

  // 初始化
  setTimeout(() => {
    currentFixedLetter.value = null
  }, 100)
})

onUnmounted(() => {
  if (listWrap.value) {
    listWrap.value.removeEventListener('scroll', throttledHandleScroll)
  }
})

// 搜索时重置高亮
watch(InputVal, () => {
  isSearchHighlighted.value = true
  selectedLetter.value = null
  currentFixedLetter.value = null
})

// 工具方法
const InputFn = () => InputRef.value?.focus()

const selectUser = (user) => {
  emit('postselectUser', user)
  model.value = false
}
</script>

<style lang="scss" scoped>
.mention_friend_component {
  @include fixed-top;
  width: 100%;
  height: 100vh;
  background-color: $secondary-color;
  z-index: 10000;

  .mention_friend_component_hd {
    @include flex-center;
    position: relative;
    color: #e8e8e9;
    height: 44px;
    line-height: 44px;
    font-size: 18px;
    z-index: 33;
    border-bottom: 0.5px solid rgba(41, 40, 37, 0.8);
    background: $secondary-color;

    .hd_lf {
      @include absolute-top-left(0, 18px);
    }
  }

  .comment_list_wrap {
    @include absolute-top-left;
    width: 100%;
    height: 100%;
    margin-top: 44px;
    overflow-y: auto;
    background: #161622;

    &::-webkit-scrollbar {
      width: 0;
      height: 0;
    }

    .comment_list_wrap_search {
      padding: 10px 20px;

      .input_wrap {
        width: 100%;
        background: #242630;
        border-radius: 5px;
        height: 44px;
        @include flex-center;
        padding: 0 8px;

        .input {
          height: 21px;
          background: #1a1b20;
          -webkit-box-flex: 1;
          -ms-flex: 1;
          flex: 1;
          font-size: 14px;
          color: #e8e8e9;
          padding-left: 10px;
          background: none;
          caret-color: #face15;
        }

        .lf,
        .rt {
          height: 100%;
          @include flex-center;
        }
      }
    }

    .list {
      padding: 10px 20px;
      display: flex;
      flex-direction: column;
      gap: 10px;

      .list_item_wrap:last-child {
        padding-bottom: 30px;
      }

      .list_item_letter {
        font-size: 14px;
        color: #fff;
        font-weight: bold;
        margin-bottom: 15px;
      }

      .list_item {
        display: flex;
        flex-direction: column;
        gap: 5px;
        align-items: start;
        margin-bottom: 20px;

        .item_letter {
          font-size: 16px;
          color: #fff;
          font-weight: bold;
        }

        .item_content {
          width: 100%;
          @include flex-center;
          justify-content: start;
          gap: 10px;

          .item_avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;

            img {
              border-radius: 50%;
            }
          }

          .item_info {
            display: flex;
            flex-direction: column;
            gap: 5px;
            font-weight: bold;

            .item_name {
              font-size: 14px;
              color: #fff;
            }

            .item_label {
              font-size: 12px;
              color: #a6a5a4;
            }
          }
        }
      }
    }
  }

  .Letterinquiry {
    @include absolute-top-right(50%, 2px);
    @include flex-center;
    transform: translateY(-50%);
    flex-direction: column;
    gap: 5px;
    padding: 10px;
    color: $white-color;

    .Letterinquiry_Icon {
      transition: all .3s ease-out;

      &.highlight {
        transform: scale(1.2);
      }
    }

    .Letterinquiry_item {
      font-size: 14px;
      color: #fff;
      font-weight: bold;
      transition: all .3s ease-out;

      &.highlight {
        color: #2180ca;
        transform: scale(1.2);
      }
    }

  }
}



.list_item_letter {
  font-size: 14px;
  color: #fff;
  font-weight: bold;
  margin-bottom: 15px;
  opacity: 0.7;
  transition: opacity 0.2s ease;
  padding: 8px 0;
  height: 30px;
  display: flex;
  align-items: center;
}

.list_item_letter.current {
  opacity: 1;
}

.fixed_letter_wrap {
  @include absolute-top-left(40px, 0);
  width: 100%;
  background: $secondary-color;
  padding: 8px 20px;
  font-size: 14px;
  color: $white-color;
  font-weight: bold;
  border-bottom: 0.5px solid rgba(41, 40, 37, 0.8);
  transition: all 0.15s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 30px;
  @include flex-center;
  z-index: 9999;

  .fixed_letter {
    display: inline-block;
    width: 100%;
    text-align: left;
    transition: all 0.15s ease;
    transform: translateZ(0);
    /* 启用硬件加速 */
  }
}
</style>